/**
 * 认证相关API接口
 */

// API基础配置
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8086';

// 请求工具函数
const request = async (url: string, options: RequestInit = {}) => {
  // 合并头部，确保不会被 options.headers 覆盖掉默认的 Content-Type
  const mergedHeaders: HeadersInit = {
    'Content-Type': 'application/json',
    ...(options.headers || {}),
  };

  const finalOptions: RequestInit = {
    credentials: 'include', // 包含cookies和session
    ...options,
    headers: mergedHeaders,
  };

  const response = await fetch(`${API_BASE_URL}${url}`, finalOptions);

  const contentType = response.headers.get('content-type') || '';
  let result: any;
  if (contentType.includes('application/json')) {
    result = await response.json();
  } else {
    const text = await response.text();
    try {
      result = JSON.parse(text);
    } catch {
      result = { code: response.status, message: text, data: null };
    }
  }

  // HTTP错误优先
  if (!response.ok) {
    throw new Error(result?.message || `HTTP ${response.status}`);
  }

  // 业务码：兼容 0 和 200 为成功
  if (typeof result?.code !== 'undefined' && ![0, 200].includes(result.code)) {
    const error = new Error(result.message || '请求失败');
    (error as any).code = result.code;
    throw error;
  }

  return result;
};

// 登录接口参数类型
export interface LoginParams {
  username: string;
  password: string;
  captcha?: string;
  captchaKey?: string;
  isQuick?: boolean;
}

// 登录响应类型
export interface LoginResponse {
  code: number;
  message: string;
  data: {
    token: string;
    refreshToken?: string;
    userInfo?: any;
  };
}

// 注册请求体类型（与后端 RegisterUserRequest 对齐）
export interface RegisterUserProfile {
  nickName?: string;
  gender?: number;
  avatar?: string;
  address?: string;
  email?: string;
  idCard?: string;
  eduDegree?: string;
  graduateSchool?: string;
  specialty?: string;
  rank?: string;
  subject?: string;
  phone?: string;
}

export interface RegisterUserPayload {
  username: string;
  password: string;
  enable: boolean;
  profile: RegisterUserProfile;
  roleIds: number[];
}

// 更新资料请求体类型（与后端 UpdateProfileRequest 对齐）
export interface UpdateProfilePayload {
  id: number; // profileId
  gender?: number; // 0 未设置，1 男，2 女
  address?: string;
  email?: string;
  nickName?: string;
}

// 认证API
export const authApi = {
  // 登录
  login: (data: LoginParams): Promise<LoginResponse> => {
    return request('/auth/login', {
      method: 'POST',
      body: JSON.stringify(data),
    });
  },

  // 注册（开放接口，不受管理员权限限制）
  register: (data: RegisterUserPayload): Promise<any> => {
    return request('/auth/register', {
      method: 'POST',
      body: JSON.stringify(data),
    });
  },

  // 获取验证码
  getCaptcha: (): string => {
    return `${API_BASE_URL}/auth/captcha?${Date.now()}`;
  },

  // 获取用户信息
  getUserInfo: (): Promise<any> => {
    const token = localStorage.getItem('token');
    return request('/user/detail', {
      headers: {
        'Authorization': `Bearer ${token}`,
      },
    });
  },

  // 获取用户详情（简化版本，复用Vue的接口）
  getUser: (): Promise<any> => {
    const token = localStorage.getItem('token');
    return request('/user/detail', {
      headers: {
        'Authorization': `Bearer ${token}`,
      },
    });
  },

  // 切换角色
  toggleRole: (data: any): Promise<any> => {
    const token = localStorage.getItem('token');
    return request('/auth/role/toggle', {
      method: 'POST',
      body: JSON.stringify(data),
      headers: {
        'Authorization': `Bearer ${token}`,
      },
    });
  },

  // 更新用户资料
  updateProfile: (userId: number, data: UpdateProfilePayload): Promise<any> => {
    const token = localStorage.getItem('token');
    return request(`/user/profile/${userId}`, {
      method: 'PATCH',
      body: JSON.stringify(data),
      headers: {
        'Authorization': `Bearer ${token}`,
      },
    });
  },
};

export default authApi;